package com.example.boot.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 *
 * @author ding
 * @since 2024/7/24
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 设置响应的字符集
        httpServletResponse.setContentType("text/html;charset=utf8");
        // 登录成功
        httpServletResponse.getWriter().println("登录成功");
        httpServletResponse.getWriter().println("用户" + authentication.getPrincipal()+"拥有权限：");
        authentication.getAuthorities().forEach(grantedAuthority -> {
            try {
                httpServletResponse.getWriter().println(grantedAuthority.getAuthority());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
